package BlockingQueue;

import java.util.Arrays;

class BQueueContainer<T> {
    private T[] arr; //数组
    private int size; //容量
    private int header; //头指针
    private int tail; //尾指针

    {
        header = tail = 0; // 初始化头尾指针
    }

    // 为了方便测试，默认容量小了点
    public BQueueContainer() {
        arr = (T[]) new Object[10];
        size = 10;
    }
    //指定容量
    public BQueueContainer(int capacity) {
        arr = (T[]) new Object[capacity];
        size = capacity;
    }

    public synchronized void put(T t) {
        // 如果容器满了就阻塞
        while ((tail + 1) % size == header) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //put one
        arr[tail++] = t;
        // tail++
        if (tail >= size) {
            tail = 0;
        }
        //notify all
        this.notifyAll();

    }

    public synchronized T get() {
        // if empty
        while ((header == 0 && tail == 0) || (header + 1) % size == tail) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // get one
        T t = arr[header++];
        // header ++
        if (header >= size) {
            header = 0;
        }
        //thread notify
        this.notifyAll();
        return t;
    }

    @Override
    public String toString() {
        return Arrays.toString(arr);
    }
}


